package com.zqh.messagemq.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;

/**
 * @Description :
 * 每个RabbitTemplate只能配置一个消息路由失败时，即所有的消息路由失败时都走这个ReturnCallback
 * RabbitTemplate是由spring容器创建的，因此需要在项目加载时配置：
 * @Author :kono淇杭哒、
 * @Create 2022-03-20 23:28
 */
@Slf4j
@Configuration
public class CommonConfig implements ApplicationContextAware{
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // 获取springbean容器中的RabbitTemplate
        RabbitTemplate rabbitTemplate = applicationContext.getBean(RabbitTemplate.class);
        // 设置ReturnCallback
        rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {
            //判断是否为延迟消息，是则忽略这个错误
            /*if(message.getMessageProperties().getReceivedDelay() > 0){
                return;
            }*/

            // 投递失败，记录日志
            log.info("消息发送失败，应答码{}，原因{}，交换机{}，路由键{},消息{}",
                    replyCode, replyText, exchange, routingKey, message.toString());

            // 如果有业务需要，可以重发消息
        });
    }
}
